<?php

namespace app\services;

use app\traits\Page;
use plugin\admin\app\model\User;
use plugin\admin\app\model\UserFollowing;
use plugin\admin\app\model\UserProfile;

class FollowingService
{
    public static function list($userId, $page = 1, $length = 10)
    {
        $offset = ($page - 1) * $length;
        $query = UserFollowing::where('user_id', $userId)->orderByDesc('created_time');

        $totalCount = (clone $query)->count();
        $list = $query->offset($offset)->limit($length)->get()->toArray();

        $userIds = array_column($list, 'following_user_id');
        $userProfiles = UserProfile::select(['user_id', 'nickname', 'avatar', 'fans_count', 'desc', 'no'])->whereIn('user_id', $userIds)->get()->toArray();

        return Page::wrap($totalCount, $page, $length, $userProfiles);
    }

    public static function follow($userId, callable $callback = null)
    {
        if ($userId == get_user_id()) {
            throw new \Exception('不能关注自己');
        }

        if (!self::isFollowing($userId)) {
            UserFollowing::insert([
                'user_id' => get_user_id(),
                'following_user_id' => $userId,
                'created_time' => date('Y-m-d H:i:s')
            ]);

            if (!is_null($callback)) {
                $callback(get_user_id(), $userId);
            }
        }
    }

    public static function isFollowing($userId)
    {
        return UserFollowing::where('user_id', get_user_id())->where('following_user_id', $userId)->count() > 0;
    }

    public static function cancelFollow($userId, callable $callback = null)
    {
        if (self::isFollowing($userId)) {
            UserFollowing::where('user_id', get_user_id())->where('following_user_id', $userId)->delete();
            if (!is_null($callback)) {
                $callback(get_user_id(), $userId);
            }
        }


    }
}